<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Command;

use _PHPStan_1b47bafe3\Nette\Utils\DateTime;
use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use App\Controller\Activity\UserRegister;
use App\Controller\Api\Repayment;
use App\Controller\Backend\Agent;
use App\Controller\Backend\Package;
use App\Controller\Backend\Remit;
use App\Exception\BusinessException;
use App\Job\ActivityCommissionJob;
use App\Job\ActivityUserInviteJob;
use App\Job\CommissionJob;
use App\Job\JPushGroupChatJob;
use App\Job\JPushSingleChatJob;
use App\Job\PushFinanacePackageNoticeJob;
use App\Job\PushGlobalNotificationJob;
use App\Job\TelephoneBalanceJob;
use App\Job\TelephoneBatchBalanceJob;
use App\Job\UserInviteJob;
use App\Job\UserLevelUpdateJob;
use App\Log\AgentLog;
use App\Log\LevelLog;
use App\Model\ActivityOrder;
use App\Model\ActivityUserInvite;
use App\Model\ActivityUserInviteGrade;
use App\Model\AgentLevel;
use App\Model\AgentOrder;
use App\Model\ChatTransact;
use App\Model\DiscountInterval;
use App\Model\ExchangeRate;
use App\Model\FinancePackageOrder;
use App\Model\Menu;
use App\Model\OrderRecord;
use App\Model\ProductOrder;
use App\Model\Setting;
use App\Model\SmsCode;
use App\Model\TelephoneOrder;
use App\Model\TopExtractOrder;
use App\Model\User;
use App\Model\UserInvite;
use App\Model\UserInviteGrade;
use App\Model\Wallet;
use App\Resource\BaseResource;
use App\Service\FinancePackageServer;
use App\Service\PayServer;
use App\Service\QueueService;
use App\Service\RateServer;
use App\Service\RemitServer;
use App\Service\SmsServer;
use App\Service\TelephoneBalanceService;
use App\Service\TopExtractService;
use App\Utils\ActivityInviteCode;
use App\Utils\InviteCode;
use GuzzleHttp\Client;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Context\ApplicationContext;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\WebSocketServer\Sender;
use Psr\Container\ContainerInterface;
use Qiniu\Auth;
use Hyperf\Coroutine\Exception\ParallelExecutionException;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Coroutine\Parallel;

#[Command]
class MakeTestCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('test');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('测试使用');
    }

    public function handle()
    {

        $a = '1';

        $smsCode = SmsCode::find(1);
        if ( (strlen($smsCode->code_four) < 5) && strlen($a) <= 4 ) {

            $smsCode->code_four = $a;
            // $smsCode->code_six = '';
        }elseif( (strlen($smsCode->code_six) < 7) &&  strlen($a) == 6 &&  strlen($a) == 5){

            $smsCode->code_six = $a;
        }

        $smsCode->save();







//        ApplicationContext::getContainer()->get(Sender::class)->push(1, '12121212');

//        \App\Model\Setting::create([
//            'id' => 14,
//            'config' => [
//                'amount' => 1000,
//                'discount' => 100
//            ],
//            'content' => '',
//            'intro' => '',
//        ]);
//        \App\Model\Setting::create([
//            'id' => 15,
//            'config' => [
//                'amount' => 100,
//            ],
//            'content' => '',
//            'intro' => '',
//        ]);
//        \App\Model\Setting::create([
//            'id' => 16,
//            'config' => [
//                10,10,10,10,10,10,10,10,10,10
//            ],
//            'content' => '',
//            'intro' => '',
//        ]);
//        \App\Model\Setting::create([
//            'id' => 17,
//            'config' => [
//                'amount' => 8,
//                'detail' => '<p><span style="color: rgb(207, 211, 220); background-color: rgb(29, 30, 31); font-size: 12px;">123</span></p>',
//                'about_us' => "<p>欢迎充值</p>",
//                'discount' => 10,
//                'amount_one' => 1,
//                'direct_amount' => 10,
//                'see_amount_ten' => 10,
//                'see_amount_two' => 2,
//                'see_amount_three' => 22,
//            ],
//            'content' => '',
//            'intro' => '',
//        ]);
//        \App\Model\Setting::create([
//            'id' => 18,
//            'config' => [
//                'notice' => '小利特惠更新迭代正式上线啦！！！',
//            ],
//            'content' => '',
//            'intro' => '首页公告',
//        ]);













//        $setting = Setting::find(20);
//
//        var_dump($setting->toArray());


//            (ApplicationContext::getContainer()->get(QueueService::class))->push(ActivityUserInviteJob::class, [
//                'uid' => 19
//            ]);





//        (new UserRegister())->registerActivityOneHandle(1, '');
//
//        for ($i = 2; $i < 12; $i++) {
//
//            (new UserRegister())->registerActivityOneHandle($i, User::find($i - 1)->activity_invite_code);
//        }
//
//
//        (new UserRegister())->registerActivityOneHandle(14, User::find(4)->activity_invite_code);
//        (new UserRegister())->registerActivityOneHandle(15, User::find(4)->activity_invite_code);
//        (new UserRegister())->registerActivityOneHandle(16, User::find(4)->activity_invite_code);
//        (new UserRegister())->registerActivityOneHandle(17, User::find(4)->activity_invite_code);
//
//        (new UserRegister())->registerActivityOneHandle(18, User::find(4)->activity_invite_code);
//        (new UserRegister())->registerActivityOneHandle(19, User::find(4)->activity_invite_code);



//          $list = TopExtractOrder::where('cert_path', 'not like', '%_clean')
//              ->where('cert_path', '!=', '')->get();





//        $count = ActivityOrder::whereIn('uid', function ($query) {
//            $query->select('uid')
//                ->from('activity_user_invite')
//                ->where('invitation_uid', 10)
//                ->get();
//        })->groupBy('uid')->get()->count();
//
//        var_dump($count);


        // ActivityUserInvite::truncate();
        // ActivityUserInviteGrade::truncate();
//        ApplicationContext::getContainer()->get(QueueService::class)->push(ActivityCommissionJob::class, [
//            'id' => 12
//        ]);

//        $amount = ActivityOrder::selectRaw('sum(real_amount) as real_amount, sum(price) as price')
//            ->where('id', '>', 0)
//            ->get();

        // $a = (ApplicationContext::getContainer()->get(TelephoneOrder::class))::find(1)->toJson()
        //
        ///
        ///
//        (new UserRegister())->registerActivityHandle(1, '');
//        for ($i = 2; $i < 20; $i++) {
//
//            (new UserRegister())->registerActivityHandle($i, '5T2SAKJJ');
//        }

       //  var_dump((new TelephoneBalanceService())->getNewTelephoneBrank(1));

//        ApplicationContext::getContainer()->get(Redis::class)->set('api_globespay_com_user_balance', 10000);

//        ApplicationContext::getContainer()->get(QueueService::class)->push(TelephoneBatchBalanceJob::class, [
//            'id' => 2269,
//        ]);

//        $parallel = new Parallel(5);
//        for ($i = 0; $i < 20; $i++) {
//            $parallel->add(function () use ($i) {
//
//                echo $i . PHP_EOL;
//                sleep(1);
//                return Coroutine::id();
//            });
//        }
//
//        try{
//            $results = $parallel->wait();
//
//            var_dump('=====$results=====');
//            var_dump($results);
//        } catch(ParallelExecutionException $e){
//            var_dump( $e->getResults() );    //获取协程中的返回值。
//            var_dump( $e->getThrowables() ); //获取协程中出现的异常。
//        }

       /*
        // 打开文件（以只读模式打开）
        $filename = BASE_PATH . '/public/29.log';
        $file = fopen($filename, 'r');

        // 检查文件是否成功打开
        if ($file) {

            $cell = 0;
            // 逐行读取文件内容
            while (($line = fgets($file)) !== false) {
                // 处理每一行的内容
                // echo $line; // 这里可以替换成你需要的处理逻辑

                $lineArr = json_decode($line, true);

                $dateTime = new DateTime($lineArr['@timestamp']);
                $formattedDate = $dateTime->format('Y-m-d H:i:s');

                Db::table('log')->insert([
                    'timestamp' => $formattedDate,
                    'upstream_response_time' => $lineArr['upstream_response_time'],
                    'request_time' => $lineArr['request_time'],
                    'request_method' => $lineArr['request_method'],
                    'request_uri' => $lineArr['request_uri'],
                    'status' => $lineArr['status'],
                    'upstream_time' => $lineArr['upstream_time'],
                    'upstream_status' => $lineArr['upstream_status']
                ]);

//                $cell++;
//                if ($cell == 10) {
//                    return;
//                }
            }

            // 关闭文件句柄
            fclose($file);
        } else {
            echo "无法打开文件: $filename";
        }


*/


        // 创建 DateTime 对象
//        $dateTime = new DateTime('2023-12-29T00:00:07+08:00');
//        $formattedDate = $dateTime->format('Y-m-d H:i:s');
//        echo $formattedDate;

//        $order = AgentOrder::with('user')->find(21);


//        $data = [
//            'bizid' => \Hyperf\Support\env('TELEPHONE_BALANCE_ID'),
//            'mobile' => 18653009825,
//            'network' => 2,
//        ];
//
//        $data['sign'] = (new TelephoneBalanceService())->sign($data);

//        var_dump($order->toArray());
//        var_dump($this->getPhoneOperotar('13353000000'));

//       $res = AgentOrder::where('uid', 1)->exists();
//
//       var_dump($res);
//        ApplicationContext::getContainer()->get(QueueService::class)->push(TelephoneBalanceJob::class, [
//            'id' => '1',
//        ]);

//        var_dump(formatNumbers(1500 * 0.0001));
//        var_dump(bcmul(formatNumbers(1500 * 0.0001), '200', 2));
//       var_dump( bcdiv( bcmul(formatNumbers(1500 * 0.0001), '200', 2), '7.3', 2) );

//        $this->getFiles();

//        $data = \App\Model\Relation\UserInvite::with('children')->where('uid', 184)->select(['uid', 'invitation_uid'])->first();
//
//        var_dump($data->toArray());


//        ApplicationContext::getContainer()->get(QueueService::class)->push(CommissionJob::class, [
//            'order_type' => OrderRecord::ORDER_TYPE_TELEPHONE,
//            'id' => 1
//        ]);

    }

    public function getPhoneOperotar($phone) {

        $isChinaMobile = "/^(?:134|135|136|137|138|139|150|151|152|157|158|159|172|178|182|183|184|187|188|195|197|198)\d{8}$/";
        $isChinaUnion = "/^(?:13[0-2]|15[56]|166|17[56]|18[56]|196)\d{8}$/";
        $isChinaTelcom = "/^(?:133|153|177|173|18[019]|190|191|193|199)\d{8}$/";
        // 移动
        if (preg_match($isChinaMobile, $phone)) {

            return new BaseResource(SuccessCode::SUCCESS, [
                'brand_name' => '中国移动',
                'brand_id' => 1,
            ]) ;
            // 联通
        } else if (preg_match($isChinaUnion, $phone)) {

            return new BaseResource(SuccessCode::SUCCESS, [
                'brand_name' => '中国联通',
                'brand_id' => 3,
            ]) ;
            // 电信
        } else if (preg_match($isChinaTelcom, $phone)) {

            return new BaseResource(SuccessCode::SUCCESS, [
                'brand_name' => '中国电信',
                'brand_id' => 2,
            ]) ;
        } else {
            throw new BusinessException(ErrorCode::CUSTOM_ERROR . '查询失败');
        }
    }

    public function getFiles()
    {

        $data = Db::table('indikator_news_posts')->find(230);

        // HTML 示例字符串
        $html = "<html>
                  <head>
                    <title>Sample HTML</title>
                  </head>
                  <body>"
                   . $data->content.
                  "</body>
                </html>
                ";

//          <a href="https://www.example.com">Example Link</a>
//
//
//                    <img src="https://www.example.com/image.jpg" alt="Example Image">

        // 创建 DOMDocument 对象
        $dom = new \DOMDocument();

        // 加载 HTML 内容
        $dom->loadHTML($html);

        // 获取所有的链接地址
        $hrefLinks = [];
        $aTags = $dom->getElementsByTagName('a');
        foreach ($aTags as $aTag) {
            $hrefLinks[] = $aTag->getAttribute('href');
        }

        // 获取所有的图像地址
        $srcLinks = [];
        $imgTags = $dom->getElementsByTagName('img');
        foreach ($imgTags as $imgTag) {
            $srcLinks[] = $imgTag->getAttribute('src');
        }

        // 打印结果
        echo "HREF Links: " . urldecode( implode(', ', $hrefLinks)) . "\n";
        echo "SRC Links: " . implode(', ', $srcLinks) . "\n";

    }

}
